/**
 * 关于协程挂起，深入，原理
 */

package com.yning.coroutines.demo.six.kotlin

import com.yning.coroutines.Log
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.concurrent.thread
import kotlin.coroutines.intrinsics.*
import kotlin.coroutines.resume

suspend fun main() {
    //six_test_one()
    //six_test_two()
    six_test_three()
    //six_test_four()
}

suspend fun six_test_one() = suspendCoroutineUninterceptedOrReturn<Int>{
    continuation ->
    Log.d(1)
    thread {
        Thread.sleep(1000)
        Log.d(2)
        continuation.resume(1024)
    }
    Log.d(3)
    COROUTINE_SUSPENDED
}

/**
 * 关于这个存在疑问：为什么这个协程会存在阻塞现象
 */
suspend fun six_test_two() {
    Log.d(1)
    Log.d(returnSuspended())
    Log.d(2)
    delay(1000)
    Log.d(3)
    Log.d(returnImmediately())
    Log.d(4)
}

// 可以通过这个例子说明，阻塞现象会出现在同一协程，在不同协程中不会出现
suspend fun six_test_three(){
    Log.d(1)
    GlobalScope.launch {
        Log.d(returnSuspended())
    }
    Log.d(2)
    delay(1000)
    Log.d(3)
    Log.d(returnImmediately())
    Log.d(4)
}

suspend fun six_test_four(){
    Log.d(returnSuspended())
}

suspend fun returnSuspended() = suspendCoroutineUninterceptedOrReturn<String>{
    continuation ->
    thread {
        Thread.sleep(1000)
        continuation.resume("Return suspended.")
    }
    COROUTINE_SUSPENDED
}

suspend fun returnImmediately() = suspendCoroutineUninterceptedOrReturn<String>{
    Log.d(1)
    "Return immediately."
}

